from __future__ import unicode_literals
from django.shortcuts import render, HttpResponse, Http404, redirect
from blog.models import Article, Comment
from datetime import date
from blog.forms import CommentForm, UserInfo
from django.core.paginator import Paginator, InvalidPage, EmptyPage, PageNotAnInteger
from django.db import connection

def index(request):
    articles = Article.objects.filter(is_recommend=True)
    articles_is_recommend = Article.objects.filter(is_recommend=False)
    page = request.GET.get('page', 1)
    per_page = 1
    paginator = Paginator(articles, per_page)
    try:
        articles = paginator.page(page)
    except (InvalidPage, EmptyPage, PageNotAnInteger) as ex:
        articles = paginator.page(1)
    print(articles)
    kwgs = {
        'articles': articles,
        'articles_is_recommend': articles_is_recommend,
    }
    return render(request,'index.html', kwgs)


def pay(request):
    return render(request, 'pay.html')

def about(request):
    return render(request, 'pay.html')

def search(request):
    # keywords = request.GET.get('s')
    keywords = request.POST.get('s')
    articles = Article.objects.filter(title__contains=keywords)
    kwgs = {"keywords": keywords,
            "articles": articles}
    print(kwgs)
    return render(request, 'search.html', kwgs)

def tag(request, tag_id):
    return render(request, 'tag.html')

def comment_post(request):
    form = CommentForm(request.POST)
    article_id = int(request.POST.get("article"))
    pid = int(request.POST.get("comment_parent"))
    if pid == 0:
        comment_pid = None
    else:
        comment_pid = Comment.objects.get(id=pid)

    if form.is_valid():
        comment = Comment.objects.create(username=form.cleaned_data["username"],
                                         email=form.cleaned_data["email"],
                                         content=form.cleaned_data["comment"],
                                         url=form.cleaned_data["url"],
                                         article_id=article_id,
                                         pid=comment_pid)
    else:
        return HttpResponse('error')

    return redirect(request.META["HTTP_REFERER"] + '#comments')

def archive(request):
    archive_articles = {}

    sql = "SELECT DISTINCT DATE_FORMAT(date_publish, '%Y-%m-%d') as col_date FROM blog_article ORDER BY date_publish"
    cursor = connection.cursor()
    cursor.execute(sql)
    year_month_dates = cursor.fetchall()
    print(year_month_dates)
    for year_month_date in year_month_dates:
        print(year_month_date)
        year_month_date = year_month_date[0]

        articles = Article.objects.filter(date_publish__startswith=year_month_date)
        print(articles)
        archive_articles[year_month_date] = articles

    kwgs = {
        "archive_articles": archive_articles
    }
    return render(request, 'archive.html', kwgs)


def blog(request, blog_id):
    form = CommentForm()
    try:
        article = Article.objects.get(pk=blog_id)
        comments = Comment.objects.filter(article_id=article.id, pid=None)
        for comment in comments:
            comment.children_comment = Comment.objects.filter(article_id=article.id, pid=comment.id)
    except Article.DoesNotExist:
        # raise Http404('not exist')
        return render(request, '404.html')
    kwgs = {"article": article,
            "form": form,
            "comment_list": comments,
            }
    return render(request, 'blog.html', kwgs)

def category(request, category_id):
    return render(request, 'category.html')

def form_test(request):
    if request.method == "GET":
        user_form = UserInfo()
        kwgs = {
            "user_form": user_form
        }
        return render(request, 'form.html', kwgs)
    else:
        user_form = UserInfo(request.POST)
        kwgs = {"user_form": user_form}

        if user_form.is_valid():
            print(user_form.cleaned_data["email"])
            print("ok")
        else:
            errors = user_form.errors
            kwgs["errors"] = errors
        return render(request, 'form.html', kwgs)